import os, sys, cv2, traceback
import numpy as np

parent_path = os.path.abspath(os.path.join(__file__, *([".."] * 3)))
sys.path.insert(0, parent_path)

import time, threading, yaml, json
from flask import Flask, request
from gevent import pywsgi, monkey, pool

from core.task.task_pipeline import TaskPipeline
from core.server import Server as BaseServer
from core.utils.logger import logging

# 打补丁，使得标准库中的阻塞式I/O操作变为非阻塞式
# monkey.patch_all()

app = Flask(__name__)


class Server(BaseServer):
    def __init__(self, server_cfg_path: str) -> None:
        super().__init__(server_cfg_path)

    def line_task(self):
        pass


# ------ 系统相关api ------


@app.route("/api/option/restart", methods=["get"])
def handle_restart():
    try:
        server.restart()
        return {"code": 200}
    except Exception as e:
        logging.error(traceback.format_exc())


# ------ 功能api ------


@app.route("/detect", methods=["post"])
def handle_detect():
    try:
        databox = {}
        try:
            code = 200
            message = ""
            logging.info(f"|detect|")
            json_data = request.json
            databox = server.main_request(data=json_data)
        except Exception as e:
            code = 500
            message = traceback.format_exc()
            logging.error(message)

        response = {
            "code": code,
            "message": message,
            "data": databox["objects"] if databox.get("objects", False) else [],
        }
        logging.info("task id {} add".format(json_data["id"]))
        response = json.dumps(response)
        return response
    except Exception as e:
        code = 500
        message = traceback.format_exc()
        logging.error(message)


if __name__ == "__main__":

    # 日志初始化
    log_path = "core/utils/logger_samples/log_cfg.yaml"
    logging.set_config(log_path)

    # 定义后台服务类
    server_cfg_path = os.path.dirname(__file__) + "/configs/server_cfg.yml"
    server = Server(server_cfg_path)

    WSGI_server = pywsgi.WSGIServer(
        ("0.0.0.0", 2682),
        app,
        # spawn=pool.Pool()
    )
    logging.info("|server start|")
    WSGI_server.serve_forever()
    logging.info("|server stop|")
